package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;


public class BookList extends ArrayList {
    private List<Book> bookList = new ArrayList<>();

    public BookList(List<Book> books) {
        this.bookList = books;
    }

    public BookList(Book... books) {
        this.bookList = Arrays.asList(books);
    }

    public BookList() {
        bookList.add(new Book(0, "testbook", BookState.AVAILABLE));
        bookList.add(new Book(1, "testbook1", BookState.AVAILABLE));
        bookList.add(new Book(2, "testbook2", BookState.CHECKED_OUT));
    }

    public List<Book> getBookList() {
        return this.bookList;
    }

    public List<Book> getAvailableBookList() {
        ArrayList<Book> result = new ArrayList<>();
        for (Book b : this.bookList) {
            if (b.isAvailable()) {
                result.add(b);
            }
        }
        return result;
    }

    public Book get(int i) {
        return bookList.get(i);
    }

    public boolean contains(int bookNumber) {
        for (Book book : bookList) {
            if (book.getNumber() == bookNumber) {
                return true;
            }
        }
        return false;
    }

    public void checkout(Book book) {
        if (storeManagesBook(book)) {
            if (book.isAvailable()) {
                book.setStatus(BookState.CHECKED_OUT);
            } else {
                throw new UnsupportedOperationException("Book already checked out!");
            }
        } else {
            throw new NoSuchElementException("No such book!");
        }
    }

    private boolean storeManagesBook(Book book) {
        return this.bookList.contains(book);
    }

    public void giveBack(Book book) {
        if (!book.isAvailable()) {
            book.setStatus(BookState.AVAILABLE);
        } else {
            throw new UnsupportedOperationException();
        }
    }

    public Book getBookById(int id) {
        for (Book b : this.bookList) {
            if (b.getNumber() == id) {
                return b;
            }
        }
        throw new NoSuchElementException("No book with id " + id);
    }
}